package git.soulbgm;

import com.espertech.esper.client.*;
import com.espertech.esper.event.map.MapEventBean;

import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.format.DateTimeFormatter;
import java.util.Locale;
import java.util.Random;

/**
 * 程序入口
 *
 * @author SoulBGM
 * @date 2024-09-12
 */
public class Application {

    private static final Random RANDOM = new Random();

    private static final DateTimeFormatter NORM_DATETIME_MS_FORMATTER = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss.SSS", Locale.getDefault()).withZone(ZoneId.systemDefault());

    public static void main(String[] args) throws InterruptedException {
        EPServiceProvider epService = EPServiceProviderManager.getDefaultProvider();

        EPAdministrator administrator = epService.getEPAdministrator();
        administrator.getConfiguration().addEventTypeAutoName("PacketSequence");

        String epl = "select sourceCode, dataType, count(packetSequence) as count from " + PacketSequence.class.getName() + ".win:time_batch(1 min) group by sourceCode,dataType order by count desc";
        EPStatement statement = administrator.createEPL(epl);
        System.out.println("开始时间 : " + NORM_DATETIME_MS_FORMATTER.format(LocalDateTime.now()));
        statement.addListener(new UpdateListener() {
            @Override
            public void update(EventBean[] eventBeans, EventBean[] eventBeans1) {
                System.out.println("结束时间 : " + NORM_DATETIME_MS_FORMATTER.format(LocalDateTime.now()));
                for (EventBean eventBean : eventBeans) {
                    Integer sourceCode = (Integer) ((MapEventBean) eventBean).getProperties().get("sourceCode");
                    Integer dataType = (Integer) ((MapEventBean) eventBean).getProperties().get("dataType");
                    Long count = (Long) ((MapEventBean) eventBean).getProperties().get("count");
                    System.out.println(sourceCode + "_" + dataType + ":" + count);
                }
            }
        });

        EPRuntime runtime = epService.getEPRuntime();
        int total = RANDOM.nextInt(100);
        System.out.println("总共：" + total);
        for (int i = 0; i < total; i++) {
            PacketSequence seq = new PacketSequence();
            seq.setSourceCode(RANDOM.nextInt(2) == 0 ? 907 : 808);
            seq.setDataType(RANDOM.nextInt(2) == 0 ? 2221 : 1299);
            seq.setPacketSequence((long) (i + 1));
            seq.setPacketDate(System.currentTimeMillis());

            runtime.sendEvent(seq);
        }
        Thread.sleep(70000);
    }
}